package com.eportal.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eportal.action.background.pojo.Page;
import com.eportal.aop.LogAnnotation;
import com.eportal.base.BaseDAO;
import com.eportal.domain.BannerResource;
import com.eportal.domain.BannerStrategy;
import com.eportal.domain.DistributeLog;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TCommunity;
import com.eportal.exception.JdbcException;
import com.eportal.service.BannerResourceService;
import com.eportal.service.TCommunityService;
import com.eportal.util.Config;
import com.eportal.util.DateUtils;
import com.eportal.util.UploadUtil;
import com.eportal.util.ValidateUtil;


@Service("bannerResourceService")
public class BannerResourceServiceImpl  implements BannerResourceService {
	private Map<String, Object> result = new HashMap<String, Object>();
	private static Logger log = Logger.getLogger(BannerResourceServiceImpl.class.getName());
	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }
	//上传资源的地址
	final static String BANNERRESOURCEPATH="/upload/bannerResource/";
	
	@Resource(name="dao")
	private BaseDAO dao;
	@Autowired
    private TCommunityService tCommunityService;
    @Override
    public BannerResource add(BannerResource bannerResource) throws Exception {
    	dao.save(bannerResource);
        return bannerResource;
    }

    @Override
    public void update(BannerResource bannerResource) throws JdbcException {
    	 dao.update(bannerResource);
    }

    @Override
    public void delete(long id) {
            BannerResource bannerResource = (BannerResource) dao.getById(BannerResource.class, id);
           dao.delete(bannerResource);
    }


    @Override
    public Page find(String where, Page page) {
        final StringBuffer hql = new StringBuffer("select * from banner_resource t left join t02_agtent a on t.agtcode=a.agtcode where 1=1 ");
        hql.append(where);
        String countsql = "select count(*) from (" + hql.toString() + ") bb";
        int count = dao.count(countsql);
        StringBuffer sb = new StringBuffer(""
        		+ "select * from "
        		+ "(select bb.*,rownum rownum_bb from "
        		+ "(select t.*,nvl(c.clickNum,0) as clickNum,a.agtName  from BANNER_RESOURCE t "
        		+ "left join (select c.resource_id,count(sid) as clickNum from banner_click c group by c.resource_id )c on c.resource_id=t.sid "
        		+ " left join t02_agtent a on t.agtcode=a.agtcode ");
        sb.append(" where 1=1 ");
        sb.append(where);
        sb.append("order by t.sid DESC ) bb where rownum<=");
        sb.append((page.getCurrentPage() * page.getPageSize()));
        sb.append(")  where rownum_bb>");
        sb.append((page.getCurrentPage() - 1) * page.getPageSize());
        List<Map<String, Object>> list = dao.queryBySql(sb.toString());
        return new Page(page.getCurrentPage(), page.getPageSize(), count, list);
    }

    @Override
    public BannerResource get(long id) {
        return (BannerResource) dao.getById(BannerResource.class, id);
    }
    

	@Override
	@LogAnnotation(operateDescribe="广告管理资源上架")  
	public Map<String, Object> addMethod(BannerResource bannerResource, File file, String fileName) {
		try {
			bannerResource.setIsOnLine(1);
			bannerResource.setSign(0);
			result = addBanner(bannerResource,file,fileName);
		} catch (Exception e) {
			 log.error("广告管理资源新增失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
		}
		return result;
	}
	
	public Map<String, Object> addBanner(BannerResource bannerResource, File file, String fileName) {
		try {
 			Sysopt user =(Sysopt)getSession().getAttribute("user");
			if (file != null) {
				boolean isImage = ValidateUtil.isImage(file);
	             if (!isImage) {
	            	 result.put("code", 0);
	            	 result.put("msg", "文件的格式不正确");
	                 return result;
	             }
	            BufferedImage image = ImageIO.read(file);
	            int width = image.getWidth();
	            int height = image.getHeight();
				int rLevel =  user.getrLevel();
	            if(rLevel==3){
	            	if(width!=750||height!=350){
		            	 result.put("code", 0);
		            	 result.put("msg", "图片尺寸不正确，请按要求重新上传");
		                 return result;
	            	}
	            }else if(rLevel==1){
	            	if(width!=750||height!=300){
		            	 result.put("code", 0);
		            	 result.put("msg", "图片尺寸不正确，请按要求重新上传");
		                 return result;	            		
	            	}
	            }
    			result = UploadUtil.uplodeFile(file,fileName,BANNERRESOURCEPATH);
    			if (!"1".equals(result.get("code").toString())) {
    				return result;
    			}
    			bannerResource.setContent(result.get("agtAttr").toString());
			}
			
			bannerResource.setcUser(Long.toString(user.getSid()));
			bannerResource.setcTime(new Date());
			int userRole =  (Integer) getSession().getAttribute("userRole");
			if (userRole == 1 || userRole == 2 || userRole == 21) {
				bannerResource.setdType("1");
			}else if (userRole == 3 || userRole == 4) {
				bannerResource.setAgtCode(user.getAgtCode());
				bannerResource.setdType("2");
	    	}else{
	    		result.put("code", 0);
	  	        result.put("msg", "权限不足，操作失败");
	    	}
			bannerResource = add(bannerResource);
			result.put("bannerResourceSid", bannerResource.getSid());
			result.put("code", 1);
            result.put("msg", "操作成功");
		} catch (Exception e) {
			 log.error("广告管理资源新增失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
		}
		return result;
	}
	
	@Override
	@LogAnnotation(operateDescribe="锁厂广告管理资源上架")  
	public Map<String, Object> addLockBannerMethod(BannerResource bannerResource, File file, String fileName,
			String priority, String timeFrom, String timeTo) {
		try {
			bannerResource.setIsOnLine(2);
			result = addBanner(bannerResource,file,fileName);
			if (!"1".equals(result.get("code").toString())) {
				return result;
			}
			String bannerResourceSid = result.get("bannerResourceSid").toString();
			BannerStrategy bannerStrategy = new BannerStrategy();
			Sysopt user =(Sysopt)getSession().getAttribute("user");
			bannerStrategy.setShid((Long)result.get("bannerResourceSid"));
			bannerStrategy.setPriority(Integer.parseInt(priority));
			bannerStrategy.setTimeFrom(DateUtils.datetimeFormat.parse(timeFrom+" 00:00:00"));
			bannerStrategy.setTimeTo(DateUtils.datetimeFormat.parse(timeTo+" 23:59:00"));
			bannerStrategy.setEnabledflag(1);
			bannerStrategy.setRange(1);
			bannerStrategy.setAgtCode(","+user.getAgtCode()+",");
			bannerStrategy.setcTime(new Timestamp(System.currentTimeMillis()));
			bannerStrategy.setcUser(user.getSid().toString());
			bannerStrategy.setBannerPosition(",1,");
			dao.save(bannerStrategy);
			//日志
			DistributeLog distributeLog = new DistributeLog();
        	distributeLog.setcTime(new Timestamp(System.currentTimeMillis()));
        	distributeLog.setcUser(Long.toString(user.getSid()));
        	distributeLog.setLogType("1");
        	distributeLog.setRange(1);
        	distributeLog.setType("0");
        	distributeLog.setAgtCode(","+user.getAgtCode()+",");
        	distributeLog.setResourcesId(bannerResourceSid);
        	dao.save(distributeLog);
		} catch (Exception e) {
			 log.error("广告管理资源新增失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
		}
		return result;
	}
	
	
	@Override
	public Map<String, String> getBySql(Long sid) {
		List<Map<String, String>> list= null;
		StringBuilder sql = new StringBuilder("select b.*,s.uname,bs.priority,to_char(bs.timeFrom,'yyyy-mm-dd') as timeFrom,to_char(bs.timeTo,'yyyy-mm-dd') as timeTo from banner_resource b left join banner_strategy bs on b.sid=bs.shid left join sysopt s on b.cuser=s.sid where b.sid=");
		sql.append(sid);
		list= dao.queryBySql(sql.toString());
		if (list.size()>0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	@LogAnnotation(operateDescribe="广告管理资源修改")  
	public Map<String, Object> updateMethod(BannerResource bannerResource, File file, String fileName) {
		try {
			result = update(bannerResource,file,fileName);
		} catch (Exception e) {
			log.error("广告管理资源修改失败", e);
            result.put("code", 0);
            result.put("msg", "操作失败");
		}
		return result;
	}

	
	public Map<String, Object> update(BannerResource bannerResource, File file, String fileName) {
		try {
			BannerResource entry = get(bannerResource.getSid());
			if (file != null) {
				boolean isImage = ValidateUtil.isImage(file);
	             if (!isImage) {
	            	 result.put("code", 0);
	            	 result.put("msg", "文件的格式不正确");
	                 return result;
	             }
    			result = UploadUtil.uplodeFile(file,fileName,BANNERRESOURCEPATH);
    			if (!"1".equals(result.get("code").toString())) {
    				return result;
    			}
    			entry.setContent(result.get("agtAttr").toString());
			}
			if (StringUtils.isNotBlank(bannerResource.getcName())) {
				entry.setcName(bannerResource.getcName());
			}
			entry.setcUrl(bannerResource.getcUrl());
			entry.setExpectedIncome(bannerResource.getExpectedIncome());
			entry.setAdDetails(bannerResource.getAdDetails());
			entry.setSettlementMethod(bannerResource.getSettlementMethod());
			if (!entry.getIfShare().equals(bannerResource.getIfShare())) {
				if("0".equals(bannerResource.getIfShare())){
					changeBannerStrategy(bannerResource.getSid(),entry.getAgtCode());
				}
			}
			entry.setType(bannerResource.getType());
			entry.setIfShare(bannerResource.getIfShare());
			Sysopt user =(Sysopt)getSession().getAttribute("user");
			entry.setuUser(Long.toString(user.getSid()));
			entry.setuTime(new Date());
			update(entry);
			result.put("code", 1);
            result.put("msg", "操作成功");
		} catch (Exception e) {
			 log.error("广告管理资源修改失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
		}
		return result;
	}
	
	@Override
	@LogAnnotation(operateDescribe="锁厂广告管理资源修改")  
	public Map<String, Object> updateLockBannerMethod(BannerResource bannerResource, File file, String fileName,
			String priority, String timeFrom, String timeTo) {
		try {
			result = update(bannerResource,file,fileName);
			if (!"1".equals(result.get("code").toString())) {
				return result;
			}
			StringBuffer sb = new StringBuffer("from BannerStrategy where shid=");
     		sb.append(bannerResource.getSid());
     		Sysopt user =(Sysopt)getSession().getAttribute("user");
     		//分配策略
     		BannerStrategy entity = (BannerStrategy) dao.loadObject(sb.toString());
			entity.setPriority(Integer.parseInt(priority));
			entity.setTimeFrom(DateUtils.datetimeFormat.parse(timeFrom+" 00:00:00"));
			entity.setTimeTo(DateUtils.datetimeFormat.parse(timeTo+" 23:59:00"));
			dao.update(entity);
			//日志
//			DistributeLog distributeLog = new DistributeLog();
//        	distributeLog.setcTime(new Timestamp(System.currentTimeMillis()));
//        	distributeLog.setcUser(Long.toString(user.getSid()));
//        	distributeLog.setLogType("1");
//        	distributeLog.setRange(1);
//        	distributeLog.setType("0");
//        	distributeLog.setAgtCode(entity.getAgtCode());
//        	distributeLog.setResourcesId(bannerResource.getSid().toString());
//        	dao.save(distributeLog);
		} catch (Exception e) {
			log.error("广告管理资源修改失败", e);
            result.put("code", 0);
            result.put("msg", "操作失败");
		}
		return result;
	}
	private void changeBannerStrategy(Long shid, String agtCode) {
		BannerStrategy bannerStrategy = getBannerStrategy(shid);
		if (bannerStrategy == null || StringUtils.isBlank(bannerStrategy.getAgtCode())|| StringUtils.isBlank(bannerStrategy.getCommunityId())) {
			return;
		}
		if(bannerStrategy.getAgtCode().indexOf(","+agtCode+",")>-1){
			bannerStrategy.setAgtCode(","+agtCode+",");
		}else{
			bannerStrategy.setAgtCode("");
			bannerStrategy.setCommunityId("");
			updateLifeStrategy(bannerStrategy);
			return;
		}
		List<TCommunity> listComu = tCommunityService.listByAgtCodes(agtCode);
		String comuIds =  bannerStrategy.getCommunityId();
		StringBuffer comuids = new StringBuffer();
		for (TCommunity tCommunity : listComu) {
			String conuid = ","+tCommunity.getSid()+",";
			if (comuIds.indexOf(conuid)>-1) {
				comuids.append(tCommunity.getSid());
				comuids.append(",");
			}
		}
		if (comuids.length()==0) {
			bannerStrategy.setAgtCode("");
			bannerStrategy.setCommunityId("");
			updateLifeStrategy(bannerStrategy);
			return;
		}
		String cmu = comuids.toString();
		bannerStrategy.setCommunityId(","+cmu);
		updateLifeStrategy(bannerStrategy);
	}

	private void updateLifeStrategy(BannerStrategy bannerStrategy) {
		dao.update(bannerStrategy);
	}

	private BannerStrategy getBannerStrategy(Long shid) {
		StringBuffer sb = new StringBuffer("from BannerStrategy where shid=");
		sb.append(shid);
		return (BannerStrategy) dao.loadObject(sb.toString());
	}
	
}
